#!/usr/bin/env python3
import requests
import sys
import argparse
import json
import hashlib
import os

__author__ = "Corsin Camichel"
__copyright__ = "Copyright 2020, Corsin Camichel"
__license__ = "Creative Commons Attribution-ShareAlike 4.0 International License."
__version__ = "1.0.0"
__email__ = "cocaman@gmail.com"

def upload_file(myfile):
    data = {
      'tags': '',
      'delivery_method': 'other'
    }
    files = {
      'json_data': (None, json.dumps(data), 'application/json'),
      'file': (open(myfile,'rb'))
    }
    print(f"Uploading file {myfile}")
    response = requests.post('https://mb-api.abuse.ch/api/v1/', files=files, headers=headers)
    json_data = json.loads(response.text)
    status = json_data['query_status']

    print("Upload status: " + status)
    if(status == "file_already_known"):
        with open(myfile,"rb") as f:
            file_bytes = f.read()
            hash_sha256 = hashlib.sha256(file_bytes).hexdigest();
            print("The report can be found here: https://bazaar.abuse.ch/sample/" + hash_sha256 + "/")

parser = argparse.ArgumentParser(description='Upload malware samples from a folder to MalwareBazaar by abuse.ch')
parser.add_argument('-d', '--directory', help='Directory name to upload files from (required)', type=str, metavar="DIRECTORY", required=True)
args = parser.parse_args()

if(os.path.isdir(args.directory) == False):
    print(f"Error, not a valid directory {args.directory}")
    exit(-1)

headers = {'API-KEY': ''}

print("Folder: " + args.directory)
with os.scandir(args.directory) as root_dir:
    for path in root_dir:
        if path.is_file():
            myfile = os.path.join(args.directory, path.name)
            upload_file(myfile)
